﻿using System;
using System.Collections;
using System.Web;
using System.Data;
using System.IO;

using BEGDC.CC.Web.UserControls;
using BEGDC.CC.BL.CCFlow.CR;
using BEGDC.CC.Entity;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.BL.Common;
using BEGDC.Utility.Castle;

namespace BEGDC.CC.Web.UserControls
{
	/// <summary>
	/// Summary description for WebUtility.
	/// </summary>
	public class WebUtility
	{
		public static void SetCurrentStatus(System.Web.UI.Page page, string currentStatus)
		{
			/* Remove State Control will load the information
			IWorkflowPage workpage = (IWorkflowPage)page;
			if (workpage != null)
				workpage.SetCurrentStatus(currentStatus);
			*/
		}

		public static int CompareCurrentStatus(System.Web.UI.Page page, string currentStatus)
		{
			IWorkflowPage workpage = (IWorkflowPage)page;
			if (workpage != null)
				return workpage.CompareStatus(currentStatus);
			return -1;
		}

		public static bool IsOngoingSte(System.Web.UI.Page page)
		{
			IWorkflowPage workpage = (IWorkflowPage)page;
			if (workpage != null)
				return workpage.IsOngoingStep();
			return false;
		}
		//public static void RedirectToExecution(int projectID, string status)
		public static void RedirectToExecution(int projectID, string qualNo,string status)
		{
			//HttpContext.Current.Response.Redirect(HttpContext.Current.BEGDC.CC.Web.UserControls.WebUtility.Path +"/Workflow/WorkflowExecution.aspx?ProjectId="+projectID.ToString(), false);
						
            if( qualNo.Trim().StartsWith("QS") )
				HttpContext.Current.Response.Redirect(BEGDC.CC.Web.UserControls.WebUtility.Path +"/CCC/CCCWorkflow.aspx?ProjectId="+projectID.ToString()+"&QualNo="+qualNo, false);
//			else if( qualNo.Trim().StartsWith("TS") )
//				HttpContext.Current.Response.Redirect(BEGDC.CC.Web.UserControls.WebUtility.Path + "/CCC/TechSupport.aspx?TSRecordId=+
			else
				HttpContext.Current.Response.Redirect(BEGDC.CC.Web.UserControls.WebUtility.Path +"/Workflow/WorkflowExecution.aspx?ProjectId="+projectID.ToString()+"&QualNo="+qualNo, false);
		}
		public static void RedirectToExecution(int projectID, string qualNo,string status, string qualType)
		{
//			string url = BEGDC.CC.Web.UserControls.WebUtility.Path;
//			switch ( qualType )
//			{
//				case BEGDC.CC.BL.Common.SysDicItem.QUAL_TYPE_CCC:
//					url += "/CCC/CCCWorkflow.aspx?ProjectId="+projectID.ToString()+"&QualNo="+qualNo;
//					break;
//				default:
//					url += "/Workflow/WorkflowExecution.aspx?ProjectId="+projectID.ToString()+"&QualNo="+qualNo;
//					break;
//			}
//			HttpContext.Current.Response.Redirect( url, false);
		}

//		public static void DisableChildrenControls(System.Web.UI.Control parentControl)
//		{
//			foreach(System.Web.UI.Control child in parentControl.Controls)
//			{
//				DisableChildrenControls(child);
//				Type type = child.GetType();
//				if (IsClassOf(type, typeof(System.Web.UI.WebControls.TextBox))
//					|| IsClassOf(type, typeof(System.Web.UI.WebControls.ListBox))
//					|| IsClassOf(type, typeof(System.Web.UI.WebControls.DropDownList))
//					|| IsClassOf(type, typeof(System.Web.UI.WebControls.CheckBox))
//					|| IsClassOf(type, typeof(System.Web.UI.WebControls.RadioButtonList))
//					|| IsClassOf(type, typeof(System.Web.UI.WebControls.RadioButton)))
//				{
//					System.Web.UI.WebControls.WebControl control = (System.Web.UI.WebControls.WebControl)child;
//					control.Enabled = false;
//					continue;
//				}
//				if (IsClassOf(type, typeof(System.Web.UI.WebControls.ImageButton))
//					|| IsClassOf(type, typeof(System.Web.UI.WebControls.Button))
//					|| IsClassOf(type, typeof(System.Web.UI.HtmlControls.HtmlImage)))
//				{
//					child.Visible = false;
//					continue;
//				}
//			}
//		}

		public static string EnCodeString(System.Web.HttpServerUtility server,string old)
		{
			return server.HtmlEncode(old).Replace(@"\",@"\\").Replace("'","@#$%").Replace("\r\n"," ");
		}

		public static string DeCodeString(System.Web.HttpServerUtility server, string old)
		{
			
			return server.HtmlDecode(old).Replace(@"\\",@"\").Replace("@#$%", "'");
		}

		public static void DisableChildrenControls(System.Web.UI.Control parentControl)
		{
			foreach(System.Web.UI.Control child in parentControl.Controls)
			{
				DisableChildrenControls(child);
				Type type = child.GetType();
				if (IsClassOf(type, typeof(System.Web.UI.WebControls.TextBox))
					|| IsClassOf(type, typeof(System.Web.UI.WebControls.ListBox))
					|| IsClassOf(type, typeof(System.Web.UI.WebControls.DropDownList))
					|| IsClassOf(type, typeof(System.Web.UI.WebControls.CheckBox))
					|| IsClassOf(type, typeof(System.Web.UI.WebControls.RadioButtonList))
					|| IsClassOf(type, typeof(System.Web.UI.WebControls.RadioButton)))
				{
					System.Web.UI.WebControls.WebControl control = (System.Web.UI.WebControls.WebControl)child;
					control.Enabled = false;
					continue;
				}
				if (IsClassOf(type, typeof(System.Web.UI.WebControls.ImageButton))
					|| IsClassOf(type, typeof(System.Web.UI.WebControls.Button)))
				{
					child.Visible = false;
					continue;
				}
				if (IsClassOf(type, typeof(System.Web.UI.HtmlControls.HtmlImage)))
				{
					System.Web.UI.HtmlControls.HtmlControl control = (System.Web.UI.HtmlControls.HtmlControl)child;
					control.Disabled = true;
					continue;
				}
			}
		}

		private static bool IsClassOf(Type objType, Type type)
		{
			if (objType.Equals(type) || objType.IsSubclassOf(type))
				return true;
			return false;
		}

		public static Employee GetUserInfo( System.Security.Principal.IPrincipal user )
		{
			BEGDC.CC.BL.Workflow.CCIdentity ui = (BEGDC.CC.BL.Workflow.CCIdentity)(( BEGDC.CC.BL.Workflow.CCPrincipal) user ).Identity;
			return ui.UserInfo;
		}

		#region ----------page redirection----------

		public static void Go2SuccessPage( System.Web.UI.Page page )
		{			
			page.Response.Redirect( BEGDC.CC.Web.UserControls.WebUtility.Path +"/main.aspx", true);
		}

		public static void Go2ChangePage( System.Web.UI.Page page )
		{			
			page.Response.Redirect( BEGDC.CC.Web.UserControls.WebUtility.Path +"/Workflow/MyChangeList.aspx", true);
		}

		public static void Go2ErrorPage( System.Web.UI.Page page, string errorCode)
		{			
			//page.Response.Redirect( BEGDC.CC.Web.UserControls.WebUtility.Path +"/Workflow/WorkflowExecution.aspx?Type=Error&error=" + errorCode, true);
            page.Response.Redirect(BEGDC.CC.Web.UserControls.WebUtility.Path + "/error/ErrorPage.aspx", true);
		}

		public static void ShowAlert( System.Web.UI.Page page, string message)
		{
			page.Response.Write("<script language=\"javascript\">\r\nalert(\"" + message +"\"); \r\n</script>");
		}

		public static void ShowConfirm( System.Web.UI.Page page, string message)
		{
			page.Response.Write("<script language=\"javascript\">\r\n if( !window.confirm(\""+message+"\") ) { event.returnValue = false; }  \r\n</script>");
		}
		public static void ExecScript( System.Web.UI.Page page, string script)
		{
			page.Response.Write("<script language=\"javascript\">\r\n" + "\r\n</script>");
		}


		#endregion

		#region ----------build ref. object----------

		#region GetDumbRole
//		public static CODMRole GetDumbRole( string roleName )
//		{
//			//临时
//			//为提高性能，可以从cached角色列表中查询
//			BEGDC.CC.BL.UserManagement.IUser usrv = AppContainer.Instance["CODMBL.User"] as BEGDC.CC.BL.UserManagement.IUser;
//			return usrv.GetRole( roleName );
//		}
		#endregion 

		#region GetDumbDic
		public static DicItem GetDumbDic( int id )
		{
			if( id >0 )
			{
				DicItem di = new DicItem();			
				di.Id = id;

				return di;
			}

			return null;
		}
		#endregion

		#endregion

		#region ----------build drop down or list box from dictionary list----------

		public static void BuildAssignmentDropDown( System.Web.UI.WebControls.DropDownList listCtrl, string UserRole, string CAT)
		{
			BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
			DataTable dataTable = utility.GetRoleMemberList(UserRole,CAT);

			if(dataTable!=null&&dataTable.Rows.Count>0)
			{
				listCtrl.DataSource = dataTable;
				listCtrl.DataValueField = "EmployeeNo";
				listCtrl.DataTextField = "Name";
				listCtrl.DataBind();
			}
		}

		public static void BuildDropDown( System.Web.UI.WebControls.DropDownList listCtrl, string dicType, bool hasNull, bool hasAll)
		{
			BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
			IList list = utility.BuildDicList( dicType);

			listCtrl.DataSource = list;
			listCtrl.DataValueField = "Id";
			listCtrl.DataTextField = "DicItemKey";
			listCtrl.DataBind();

			if( hasNull )
			{
				listCtrl.Items.Insert(0,new System.Web.UI.WebControls.ListItem("","-1"));
			}
			if( hasAll )
			{
				listCtrl.Items.Insert(0,new System.Web.UI.WebControls.ListItem("All","0"));
			}

		}

		public static void BuildDropDown( System.Web.UI.WebControls.DropDownList listCtrl, string dicType, bool hasNull, bool hasAll, bool setDefault)
		{
			BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
			IList list = utility.BuildDicList( dicType);

			listCtrl.DataSource = list;
			listCtrl.DataValueField = "Id";
			listCtrl.DataTextField = "DicItemKey";
			listCtrl.DataBind();

			if( hasNull )
			{
				listCtrl.Items.Insert(0,new System.Web.UI.WebControls.ListItem("","-1"));
			}
			if( hasAll )
			{
				listCtrl.Items.Insert(0,new System.Web.UI.WebControls.ListItem("All","0"));
			}
//			if( setDefault )
//			{
//				foreach( DicItem item in list )
//				{
//					if( item.IsDefault )
//					{
//						listCtrl.SelectedValue = item.Id.ToString();
//						break;
//					}
//				}
//			}

		}

		public static void BuildCheckBoxList( System.Web.UI.WebControls.CheckBoxList CbList, string dicType)
		{
			BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
			IList list = utility.BuildDicList( dicType);

			CbList.DataSource = list;
			CbList.DataValueField = "Id";
			CbList.DataTextField = "DicItemKey";
			CbList.DataBind();
		}

		public static void BuildListBox( System.Web.UI.WebControls.ListBox listCtrl, string dicType)
		{
			BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
			IList list = utility.BuildDicList( dicType);

			listCtrl.DataSource = list;
			listCtrl.DataValueField = "Id";
			listCtrl.DataTextField = "DicItemKey";
			listCtrl.DataBind();

		}

		#endregion

		#region ----------check role----------

		#region IsInRoles
		/// <summary>
		/// Check whether the user is in specified role list.
		/// </summary>
		/// <param name="user">Current HTTP context user</param>
		/// <param name="roles">Roles to search in.</param>
		/// <returns>True if the user is in all of the roles; otherwise False.</returns>
		public static bool IsInRoles( System.Security.Principal.IPrincipal user, string[] roles )
		{
			string str = "";

			for( int i=0; i< roles.Length ; i++)
			{
				str += roles[i] + "&";
			}
			str = str.Trim('&');
	
			//调用底层接口，执行验证
			//查询项目成员列表或者角色列表
			return user.IsInRole( str );
		}

		/// <summary>
		/// Check whether the user is in specified role list of the given project flow.
		/// </summary>
		/// <param name="user">Current HTTP context user</param>
		/// <param name="flowId">Project flow ID.</param>
		/// <param name="roles">Roles to search in.</param>
		/// <returns>True if the user is in all of the roles; otherwise False.</returns>
		public static bool IsInRoles( System.Security.Principal.IPrincipal user, long flowId, string[] roles )
		{

			//调用底层接口，执行验证
			//查询项目成员列表或者角色列表
			BEGDC.CC.BL.Workflow.CCPrincipal cuser = (BEGDC.CC.BL.Workflow.CCPrincipal) user;

			bool isIn = true;
			for( int i=0; i< roles.Length; i++ )
			{
				if( !cuser.IsInRole( roles[i], flowId ) )
				{
					isIn = false;
					break;
				}				
			}		 

			return isIn;
		}		

		/// <summary>
		/// Check whether the user is in specified role list of the given project flow.
		/// </summary>
		/// <param name="user">Current HTTP context user</param>
		/// <param name="projectId">Project ID.</param>
		/// <param name="roles">Roles to search in.</param>
		/// <returns>True if the user is in all of the roles; otherwise False.</returns>
		public static bool IsInRoles( System.Security.Principal.IPrincipal user, int projectId, string[] roles )
		{

			//调用底层接口，执行验证
			//查询项目成员列表或者角色列表
			BEGDC.CC.BL.Workflow.CCPrincipal cuser = (BEGDC.CC.BL.Workflow.CCPrincipal) user;

			bool isIn = true;
			for( int i=0; i< roles.Length; i++ )
			{
				if( !cuser.IsInRole( roles[i], projectId ) )
				{
					isIn = false;
					break;
				}				
			}		 

			return isIn;
		}		


		#endregion

		#region IsNotInRoles
		/// <summary>
		/// Check whether the user is not in any of the roles.
		/// </summary>
		/// <param name="user">Current HTTP context user</param>
		/// <param name="roles">Roles to search in.</param>
		/// <returns>True if the user is not in any of the roles; otherwise False.</returns>
		public static bool IsNotInRoles( System.Security.Principal.IPrincipal user, string[] roles )
		{
			string str = "";
	
			// any of the role
			for( int i=0; i< roles.Length ; i++)
			{
				str += roles[i] + "|";
			}
			str = str.Trim('|');	
		

			//调用底层接口，执行验证
			//查询项目成员列表或者角色列表

			return !user.IsInRole( str );			
		}

		public static bool IsNotInTSRoles( System.Security.Principal.IPrincipal user, long flowId, string[] roles)
		{
			//调用底层接口，执行验证
			//查询项目成员列表或者角色列表
			BEGDC.CC.BL.Workflow.CCPrincipal cuser = (BEGDC.CC.BL.Workflow.CCPrincipal) user;
			bool isIn = true;
			for( int i=0; i< roles.Length; i++ )
			{
				// if in any of the role, get False		
				if( cuser.IsInTSRole( roles[i], flowId ) )
				{
					isIn = false;
					break;
				}							
			}		 

			return isIn;	
		}

		/// <summary>
		/// Check whether the user is not in any of the roles of specified project flow.
		/// </summary>
		/// <param name="user">Current HTTP context user</param>
		/// <param name="flowId">Project flow ID.</param>
		/// <param name="roles">Roles to search in.</param>
		/// <returns>True if the user is not in any of the roles; otherwise False.</returns>
		public static bool IsNotInRoles( System.Security.Principal.IPrincipal user,long flowId, string[] roles )
		{
			//调用底层接口，执行验证
			//查询项目成员列表或者角色列表
			BEGDC.CC.BL.Workflow.CCPrincipal cuser = (BEGDC.CC.BL.Workflow.CCPrincipal) user;

			bool isIn = true;
			for( int i=0; i< roles.Length; i++ )
			{
				// if in any of the role, get False		
				if( cuser.IsInRole( roles[i], flowId ) )
				{
					isIn = false;
					break;
				}							
			}		 

			return isIn;			
		}

		/// <summary>
		/// Check whether the user is not in any of the roles of specified project flow.
		/// </summary>
		/// <param name="user">Current HTTP context user</param>
		/// <param name="projectId">Project ID.</param>
		/// <param name="roles">Roles to search in.</param>
		/// <returns>True if the user is not in any of the roles; otherwise False.</returns>
		public static bool IsNotInRoles( System.Security.Principal.IPrincipal user,int projectId, string[] roles )
		{
			//调用底层接口，执行验证
			//查询项目成员列表或者角色列表
			BEGDC.CC.BL.Workflow.CCPrincipal cuser = (BEGDC.CC.BL.Workflow.CCPrincipal) user;

			bool isIn = true;
			for( int i=0; i< roles.Length; i++ )
			{
				// if in any of the role, get False		
				if( cuser.IsInRole( roles[i], projectId ) )
				{
					isIn = false;
					break;
				}							
			}		 

			return isIn;			
		}
		#endregion

		#region IsAtSteps
		public static bool IsAnyStep( string myStep, string[] steps)
		{
			bool isAt = false;

			for( int i=0 ; i< steps.Length ; i++ )
			{
				if( myStep.Equals( steps[i] ) ) 
				{
					isAt = true;
					break;
				}
			}

			return isAt;
		}
		#endregion

		#endregion

		#region ----------check access ----------

		[FlagsAttribute]
			public enum AccessConst
		{
			None = 0,
			ReadOnly = 1,
			Edit = 2,
			Submit = 4,
			Delete = 8,
			Full = 14
		}
		public enum LoginType
		{
			None = 0,
			Viewer,
			Owner
		}

		public enum StepAttribute
		{
			Normal = 0,
			Ongoing = 1,
			CRUpdate = 2,
			CRRedoOngoing = 5
		}
		public static bool HasAccess( AccessConst access, AccessConst access2Find )
		{
			if( (access & access2Find) == access2Find )
				return true;
			else
				return false;
		}

		public static WebUtility.StepAttribute CheckStepAttribute( System.Web.UI.Page page, int projectId, string flowStep, out int changeTaskId )
		{
			/*

			bool isOngoing = WebUtility.IsOngoingSte( page );
			changeTaskId = 0;

			BEGDC.CC.BL.QualFlow.CQ.IProject prjsrv = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.ProjectService] as BEGDC.CC.BL.QualFlow.CQ.IProject ;

			string sql;
			sql = "select top 1 * from viewChangeInfo where Flag<>'"+ Resource.Workflow.Keys.End +"' and ProjectID=" + projectId.ToString();
			DataTable change = prjsrv.ExecuteSearch( sql );

			// No change is happening
			if( change == null || change.Rows.Count==0 )
			{
				if( isOngoing ) return WebUtility.StepAttribute.Ongoing;
				else
					return WebUtility.StepAttribute.Normal;
			}

			// One change is happening
			sql = "select * from viewActiveCRTask where ChangeID=" + change.Rows[0]["ChangeID"].ToString();
			DataTable crtask = prjsrv.ExecuteSearch( sql );

			bool isCR_reset = false;
			bool isCR_update = false;

			// Change implementation is happening
			if( crtask != null && crtask.Rows.Count>0 )
			{
				//临时
				crtask.DefaultView.RowFilter = "TaskType = 'ResetFlow'";
				if( crtask.DefaultView.Count > 0 )// CR: reset flow
				{
					isCR_reset = true;
				}
				crtask.DefaultView.RowFilter = "TaskType <> 'ResetFlow' and IsTaskOk<>1 and Task = '" + flowStep + "'";
				if( crtask.DefaultView.Count > 0 )// CR: update info at this step
				{
					isCR_update = true;
					changeTaskId = Convert.ToInt32( crtask.DefaultView[0]["TaskID"] );
				}

				//CR:流程重置，此环节为流程当前环节
				if( isCR_reset && isOngoing ) return WebUtility.StepAttribute.CRRedoOngoing;			
			
				//CR: 此环节需要修改信息
				if( isCR_update )
				{
					//CR:流程暂停，此环节允许修改
					if( !isCR_reset ) 
						return WebUtility.StepAttribute.CRUpdate;	
		
						//CR:流程重置，根据此环节的位置判断是否允许修改
					else 
					{
						//判断是当前步骤之前还是之后。如果之前，允许编辑；否则只读
						int pos = WebUtility.CompareCurrentStatus( page, flowStep );
						if( pos < 0 ) // previous
							return WebUtility.StepAttribute.CRUpdate;				
					}
				}

			}

			//Other cases, all normal (Readonly)
			return WebUtility.StepAttribute.Normal;

			*/
			changeTaskId = 0;
			return WebUtility.StepAttribute.Normal;
		}


		#endregion

		#region CR Specified Methods
		public static void BuildVehicleType( System.Web.UI.WebControls.DropDownList listCtrl, string Source)
		{
			ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
			IList list = CRService.GetVehicleTypes(Source);

			if(list!=null&&list.Count>0)
			{
				listCtrl.DataSource = list;
				listCtrl.DataValueField = "Id";
				listCtrl.DataTextField = "VehicleTypeName";
				listCtrl.DataBind();
			}
			if(listCtrl.Items.Count>0)
			{
				listCtrl.Items[0].Selected = true;
			}
		}

		public static void BuildHotel( System.Web.UI.WebControls.DropDownList listCtrl)
		{
			ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
			IList list = CRService.GetHotels();

			if(list!=null&&list.Count>0)
			{
				listCtrl.DataSource = list;
				listCtrl.DataValueField = "Id";
				listCtrl.DataTextField = "HotelNameCN";
				listCtrl.DataBind();
			}
		}

		public static void BuildHotelRoomTypes( System.Web.UI.WebControls.DropDownList listCtrl, int HotelId)
		{
			ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
			IList list = CRService.GetHotelRoomTypes(HotelId);

			if(list!=null&&list.Count>0)
			{
				listCtrl.DataSource = list;
				listCtrl.DataValueField = "Id";
				listCtrl.DataTextField = "RoomType";
				listCtrl.DataBind();
			}
			if(listCtrl.Items.Count>0)
			{
				listCtrl.Items[0].Selected = true;
			}
		}
		#endregion

		//=====================================Format data string  ===============================
		public static string FormatDateString( DateTime date )
		{
			return date.ToString("MM/dd/yyyy");
		}
		public static string FormatEffortString( double effort )
		{
			return effort.ToString( "#0.#####" );
		}
		public static string FormatPriceString( decimal price )
		{
			if( price == 0 )
				return "0";

			return price.ToString("#0..#####");
		}

		public static DataTable ConvertStatusString(DataTable table, string column)
		{
			if( table != null )
			{
				foreach( DataRow row in table.Rows )
				{
					if ( row[column] != System.DBNull.Value )
					{
						row[column] = row[column].ToString();
					}
				}
			}

			return table;
		}

		public static DataTable ConvertStatusString(IList list)
		{
			DataTable table = new DataTable();
//			table.Columns.Add("Text");
//			table.Columns.Add("Value");
//
//			if( list != null )
//			{
//				for(int i=0; i<list.Count; i++)
//				{
//					if ( ((DicItem)list[i]).KeyValue != string.Empty )
//					{
//						DataRow row = table.NewRow();
//						row["Text"] = ((DicItem)list[i]).KeyValue;
//						row["Value"] = ((DicItem)list[i]).KeyValue;
//						table.Rows.Add(row);
//					}
//				}
//			}

			return table;
		}

		public static string ConvertStatusString(string key)
		{
			return key;
//			return GDC.CODM.Resource.Workflow.Keys.GetString( key );
		}

		public static string ConvertStringByFileInfoResource(string key)
		{
			return key;
//			return GDC.CODM.Resource.FileInfo.Keys.GetString( key );
		}

		public static string Path
		{
			get
			{
				string path = HttpContext.Current.Request.ApplicationPath;
				if (path == "/")
					return string.Empty;
				return path;
			}
		}

		public static int GetColumnWidth(string columnName)
		{
			switch(columnName)
			{
				case "QualNo":
					return 150;
				case "DR2Date":
					return 100;
				case "PriorityText":
					return 50;
				case "AMK":
					return 150;
				case "AMKReportNo":
					return 100;
				case "AMKStatusText":
					return 80;
				case "ApplicantText":
					return 80;
				case "APN":
					return 250;
				case "ProjectStatus":
					return 150;
				case "CurrentOwner":
					return 100;
				case "Family":
					return 120;
				case "Product":
					return 100;
				case "Manufacturer":
					return 120;
				case "CEEngineer":
					return 100;
				case "RegisterDate":
					return 100;
				case "TQPlanDate":
					return 100;
				case "TQDate":
					return 100;
				case "IQDate":
					return 100;
				case "CQDate":
					return 100;
				case "StatusFlag":
					return 100;
				case "ProjectOwner":
					return 100;
				default:
					return 100;
			}
		}

		static public string GetDocumentStoredPath(string rootPath, string fileName, out string fullPath)
		{
			string path = System.IO.Path.Combine(rootPath, DateTime.Now.ToString("yyMMdd"));
			if (!Directory.Exists(path)) Directory.CreateDirectory(path);

			string prefix = GetDocFilePrefix(path);
			string relativePath = DateTime.Now.ToString("yyMMdd") + "\\" + prefix + "_" + System.IO.Path.GetFileName(fileName);
 
			fullPath = System.IO.Path.Combine(path, prefix + "_" + System.IO.Path.GetFileName(fileName));	
			return relativePath;
		}

		static private string GetDocFilePrefix(string path)
		{
			int max = 0;
			string[] files = Directory.GetFiles(path);
			if (files.Length > 0)
			{
				ArrayList al = new ArrayList(files);
				al.Sort();
				string name = System.IO.Path.GetFileName(al[al.Count - 1].ToString());
				string prefix = name.Substring(0, 4);
				max = Convert.ToInt32(prefix);
			}
			++max;
			return max.ToString("d4");
		}

		static public bool IsNumber(string number)
		{
			try
			{
				decimal temp = Convert.ToDecimal(number);
				return true;
			}
			catch
			{
				return false;
			}
		}
	}

}
